package com.example.server;

import com.example.config.MqttServerConfig;
import com.example.handler.MqttServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.InputStream;
import java.security.KeyStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.example.handler.TcpMessageDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolConfig;
import com.example.codec.MqttWebSocketCodec;

@Component
public class MqttServer {
    private final MqttServerConfig config;
    private final ApplicationContext applicationContext;
    private final ResourceLoader resourceLoader;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private static final Logger log = LoggerFactory.getLogger(MqttServer.class);

    public MqttServer(MqttServerConfig config, 
                     ApplicationContext applicationContext,
                     ResourceLoader resourceLoader) {
        this.config = config;
        this.applicationContext = applicationContext;
        this.resourceLoader = resourceLoader;
    }

    @PostConstruct
    public void start() throws Exception {
        bossGroup = new NioEventLoopGroup(config.getBossThreads());
        workerGroup = new NioEventLoopGroup(config.getWorkerThreads());

        // 启动局域网服务器
        if (config.getNetwork().getLan().isEnabled()) {
            // MQTT
            if (config.getNetwork().getLan().getMqtt().isEnabled()) {
                startMqttServer(config.getNetwork().getLan().getHost(),
                              config.getNetwork().getLan().getMqtt().getPort(),
                              null);
            }
            // WebSocket
            if (config.getNetwork().getLan().getWs().isEnabled()) {
                startWsServer(config.getNetwork().getLan().getHost(),
                            config.getNetwork().getLan().getWs().getPort(),
                            config.getNetwork().getLan().getWs().getPath(),
                            null);
            }
        }

        // 启动广域网服务器
        if (config.getNetwork().getWan().isEnabled()) {
            SslContext sslContext = null;
            if (config.getNetwork().getWan().getSsl().isEnabled()) {
                sslContext = createSslContext();
            }
            // MQTTS
            if (config.getNetwork().getWan().getMqtt().isEnabled()) {
                startMqttServer(config.getNetwork().getWan().getHost(),
                              config.getNetwork().getWan().getMqtt().getPort(),
                              sslContext);
            }
            // WSS
            if (config.getNetwork().getWan().getWs().isEnabled()) {
                startWsServer(config.getNetwork().getWan().getHost(),
                            config.getNetwork().getWan().getWs().getPort(),
                            config.getNetwork().getWan().getWs().getPath(),
                            sslContext);
            }
        }
    }

    private void startMqttServer(String host, int port, SslContext sslContext) throws Exception {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    if (sslContext != null) {
                        ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
                    }
                    ch.pipeline().addLast(
                        new MqttDecoder(config.getMaxMessageSize()),
                        MqttEncoder.INSTANCE,
                        applicationContext.getBean(MqttServerHandler.class)
                    );
                }
            })
            .option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, true);

        b.bind(host, port).sync();
        log.info("MQTT server started on {}:{}", host, port);
    }

    private void startWsServer(String host, int port, String path, SslContext sslContext) throws Exception {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    if (sslContext != null) {
                        ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
                    }
                    ch.pipeline().addLast(
                        new HttpServerCodec(),
                        new HttpObjectAggregator(65536),
                        new WebSocketServerProtocolHandler(WebSocketServerProtocolConfig.newBuilder()
                            .websocketPath(path)
                            .subprotocols("mqtt")
                            .allowExtensions(true)
                            .build()),
                        new MqttWebSocketCodec(),
                        new MqttDecoder(config.getMaxMessageSize()),
                        MqttEncoder.INSTANCE,
                        applicationContext.getBean(MqttServerHandler.class)
                    );
                }
            })
            .option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, true);

        b.bind(host, port).sync();
        log.info("WebSocket server started on {}:{}{}", host, port, path);
    }

    private SslContext createSslContext() throws Exception {
        if (!config.getNetwork().getWan().getSsl().isEnabled()) {
            return null;
        }
        
        Resource keystoreResource = resourceLoader.getResource(
            config.getNetwork().getWan().getSsl().getKeyStore());
            
        if (!keystoreResource.exists()) {
            log.warn("SSL keystore not found, SSL will be disabled");
            return null;
        }
        
        try (InputStream keystoreStream = keystoreResource.getInputStream()) {
            KeyStore keyStore = KeyStore.getInstance("JKS");
            String keyStorePassword = config.getNetwork().getWan().getSsl().getKeyStorePassword();
            keyStore.load(keystoreStream, keyStorePassword.toCharArray());
            
            return SslContextBuilder.forServer(
                ((KeyStore.PrivateKeyEntry) keyStore.getEntry(
                    "server", 
                    new KeyStore.PasswordProtection(keyStorePassword.toCharArray())
                )).getPrivateKey(),
                (java.security.cert.X509Certificate) keyStore.getCertificate("server")
            ).build();
        }
    }

    @PreDestroy
    public void stop() {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
    }
} 